<template>
  <el-drawer direction="rtl" v-model="dialogVisible" :title="dialogTitle" size="70%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
    <el-row>
      <el-col :span="12">
        <el-form-item label="开户姓名" prop="memberUserName">
          <template v-if="formData.id != null">
              {{ formData.memberUserName }}
          </template>
          <template v-else>
            <el-input v-model="formData.memberUserName" :readonly="true">
              <template #append>
                <el-button @click="openSelectMember" v-if="formData.id == null || formData.id == undefined">选择</el-button>
                <el-button @click="clearSelectMember">清空</el-button>
              </template>
            </el-input>
          </template>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="配置描述" prop="configRemark">
          <el-input v-model="formData.configRemark" placeholder="请输入配置描述" />
        </el-form-item>
      </el-col>
     </el-row>
      <template v-if="formData.id != null || formData.id != undefined">
        <el-alert
          title="转账绑定，次日自动转账账户"
          type="success"
          :closable="false"
          style="margin-bottom: 10px"
        />
      <el-row>
        <el-col :span="12">
          <el-form-item label="商户编号" prop="matCode">
            <el-input v-model="formData.matCode" placeholder="请输入商户编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商户有效期" prop="matExpiresTime">
            <el-date-picker
              clearable
              v-model="formData.matExpiresTime"
              type="date"
              value-format="x"
              placeholder="选择商户有效期"
            />
          </el-form-item>
        </el-col>
      </el-row>
        <el-alert
          title="电费参数设置"
          type="success"
          :closable="false"
          style="margin-bottom: 10px"
        />
        <el-form-item label="提醒设置" prop="warnElecMoney">
          <el-input-number v-model="formData.warnElecMoney" :precision="0" />
          <span style="color: red">当电表余额小于该值时消息提醒</span>
        </el-form-item>
        <el-form-item label="最少充值" prop="minPayElecCharge">
          <el-input-number
            v-model="formData.minPayElecCharge"
            placeholder="请输入最少支付（元）"
            :precision="0"
          />
          <span style="color: red">房东名下所有电表充值最低限额</span>
        </el-form-item>
        <el-alert
          title="平台手续费设置（扣除银联之外）"
          type="success"
          :closable="false"
          style="margin-bottom: 10px"
        />
        <el-form-item label="房租" prop="platformRentBillPayRate">
          <el-input v-model.trim="formData.platformRentBillPayRate" :max="1">
            <template #append>
              <el-button type="success">%——百分比</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="电费" prop="platformElecChargeRate">
          <el-input v-model.trim="formData.platformElecChargeRate" :max="1">
            <template #append>
              <el-button type="success">%——百分比</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="水费" prop="platformWaterPayRate">
          <el-input v-model.trim="formData.platformWaterPayRate" :max="1">
            <template #append>
              <el-button type="success">%——百分比</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="宽带" prop="platformNetPayRate">
          <el-input v-model.trim="formData.platformNetPayRate" :max="1">
            <template #append>
              <el-button type="success">%——百分比</el-button>
            </template>
          </el-input>
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>

  <MemberUserSelect ref="openSelectMemberRef" @confirm-member-user="confirmMemberUser" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { divide } from '@/utils/tools'
import * as OwnMeterConfigApi from '@/api/zwsj/ownMeterConfig'
import MemberUserSelect from '@/views/zwsj/common/MemberUserSelect.vue'

defineOptions({ name: 'OwnMeterConfigForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  memberUserId: undefined,
  memberUserName: undefined,
  configRemark: undefined,
  platformElecChargeRate: undefined,
  platformNetPayRate: undefined,
  platformWaterPayRate: undefined,
  platformRentBillPayRate: undefined,
  minPayElecCharge: undefined,
  payFeeStyle: 0,
  matCode: undefined,
  matExpiresTime: undefined,
  warnElecMoney: undefined,
  lastOperIp: undefined,
  lastOperDate: undefined
})
const formRules = reactive({
  memberUserName: [
    {
      required: true,
      message: '会员ID不能为空',
      trigger: 'blur'
    }
  ],
  matCode: [
    {
      required: true,
      message: '商户编号不能为空',
      trigger: 'blur'
    }
  ],
  matExpiresTime: [
    {
      required: true,
      message: '商户有效期不能为空',
      trigger: 'blur'
    }
  ],
  platformElecChargeRate: [
    {
      required: true,
      message: '电费充值平台手续费不能为空',
      trigger: 'blur'
    }
  ],
  platformNetPayRate: [
    {
      required: true,
      message: '宽带充值平台手续费不能为空',
      trigger: 'blur'
    }
  ],
  minPayElecCharge: [
    {
      required: true,
      message: '最少支付（元）不能为空',
      trigger: 'blur'
    }
  ],
  warnElecMoney: [
    {
      required: true,
      message: '提醒设置不能为空',
      trigger: 'blur'
    }
  ],
  payFeeStyle: [
    {
      required: true,
      message: '手续费负担不能为空',
      trigger: 'blur'
    }
  ]
})
// 数据字典
const elecPayFeeStyleDictDatas = getIntDictOptions(DICT_TYPE.ELEC_PAY_FEE_STYLE)
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      if (type === 'update') {
        let data = await OwnMeterConfigApi.getOwnMeterConfig(id)
        formData.value = data
        formData.value.warnElecMoney = parseInt(divide(formData.value.warnElecMoney, 100))
        formData.value.minPayElecCharge = parseInt(divide(formData.value.minPayElecCharge, 100))
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OwnMeterConfigApi.OwnMeterConfigVo
    if (formType.value === 'create') {
      await OwnMeterConfigApi.createOwnMeterConfig(data)
      message.success(t('common.createSuccess'))
    } else {
      await OwnMeterConfigApi.updateOwnMeterConfig(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    memberUserId: undefined,
    memberUserName: undefined,
    configRemark: undefined,
    minPayElecCharge: undefined,
    platformWaterPayRate: undefined,
    platformRentBillPayRate: undefined,
    payFeeStyle: 0,
    matCode: undefined,
    matExpiresTime: undefined,
    warnElecMoney: undefined,
    lastOperIp: undefined,
    lastOperDate: undefined
  }
  //formRef.value?.resetFields()
}

// 选择房东
const openSelectMemberRef = ref()
const openSelectMember = async () => {
  openSelectMemberRef.value.open()
}

const confirmMemberUser = async (memberUser: any) => {
  formData.value.memberUserId = memberUser.id
  formData.value.memberUserName = memberUser.nickname
}

const clearSelectMember = async () => {
  formData.value.memberUserId = undefined
  formData.value.memberUserName = undefined
}
</script>
